package com.infore.operation.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageHelper;
import com.infore.operation.entity.*;
import com.infore.operation.entity.vo.LoginUser;
import com.infore.operation.exception.OperationException;
import com.infore.operation.mapper.StatisticsMapper;
import com.infore.operation.mapper.UserMapper;
import com.infore.operation.service.UserService;
import com.infore.operation.utils.FileUtil;
import com.infore.operation.utils.FormatUtil;
import com.infore.operation.utils.VerifyCodeUtil;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author:wk
 * @date:Created in 14:06 2018\4\16 0016
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StatisticsMapper statisticsMapper;

    @Value("${imagePath}")
    private String  imagePath;

    @Value("${photoPath}")
    private String  photoPath;

    private CacheManager cacheManager = CacheManager.newInstance();

    @Override
    public LoginUser login(String account, String password) {
        User checkUser = userMapper.getLoginUserByAccount(account);
        if (checkUser == null){
            throw new OperationException("账号不存在！");
        }
        User user = userMapper.getLoginUser(account,FormatUtil.string2MD5(password));
        if (user!=null){
            LoginUser loginUser = new LoginUser();
            loginUser.setId(user.getId());
            loginUser.setAddress(user.getAddress());
            loginUser.setDiscrib(user.getDiscrib());
            loginUser.setEduc(user.getEduc());
            loginUser.setEntryT(user.getEntryT());
            loginUser.setStepcode(user.getStepcode());
            loginUser.setGender(user.getGender());
            loginUser.setLevel(user.getLevel());
            loginUser.setLevelName(user.getLevelName());
            loginUser.setLat(user.getLat());
            loginUser.setLnt(user.getLnt());
            loginUser.setName(user.getName());
            loginUser.setLoginAcc(user.getLoginAcc());
            loginUser.setPcOrig(user.getPcOrig());
            loginUser.setTel(user.getTel());
            loginUser.setRole(user.getRole());
            //设置默认不是上级
            loginUser.setHeadQuartor(false);
            //设置默认不是上级
            loginUser.setUpper(0);
            if (user.getStepcode() != null
                    && user.getStepcode().startsWith("001")) {
                loginUser.setHeadQuartor(true);
                loginUser.setUpper(1);
            }
            Ehcache cache = cacheManager.getEhcache("ehCache");
            String id = user.getId().toString();
            System.out.println(cache.get(id)==null?"":cache.get(id).getObjectValue());
            String token = FormatUtil.string2MD5(id+new Date().toString());
            cache.put(new Element(id,token));
            String level =user.getLevel().toString();
            List<Integer> menuList = new ArrayList<Integer>();
            if ("1".equals(level)
                    || "9".equals(level)) {
                menuList.add(1);
                menuList.add(3);
                menuList.add(4);
                menuList.add(5);
                menuList.add(6);
                menuList.add(7);
                menuList.add(8);
                menuList.add(9);
                menuList.add(10);
                menuList.add(14);
                menuList.add(15);
            } else if ("5".equals(level)
                    || "6".equals(level)
                    || "7".equals(level)) {
                menuList.add(1);
                menuList.add(2);
                menuList.add(3);
                menuList.add(4);
                menuList.add(5);
                menuList.add(6);
                menuList.add(7);
                menuList.add(8);
                menuList.add(9);
                menuList.add(10);
                menuList.add(14);
                menuList.add(15);
            } else {
                menuList.add(2);
                menuList.add(6);
                menuList.add(7);
                menuList.add(8);
                menuList.add(9);
                menuList.add(10);
            }
            if (user.getRole()!= null
                    &&!"2".equals(user.getRole().toString())) {
                menuList.add(11);
            }
            if ("10".equals(level)
                    || "11".equals(level)
                    || "18".equals(level)
                    || "19".equals(level)
                    || "31".equals(level)||"37".equals(level)) {
                menuList.add(12);
            }
            if ("35".equals(level)) {
                menuList.add(12);
            }
            menuList.add(13);
            loginUser.setMenuList(menuList);
            String pic = user.getPic();
            if (pic != null && !pic.equals("")) {
                String name = pic;
                File fileDir = new File(photoPath);
                try {
                    FileUtil.judeFileExists(fileDir);
                    byte bytes[] = user.getPicImg();
                    FileUtil.createFile(photoPath,bytes,name);
                    StringBuffer sb = new StringBuffer();
                    loginUser.setPic(
                            sb.append("http://").append(imagePath).append("/OMMS-Image/")
                                    .append(name)
                                    .toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                loginUser.setPic("");
            }
            return loginUser;
        }
        return null;
    }

    @Override
    public List<Person> queryLowPson(String userId) {
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
        if (infoId == null){
            throw new OperationException("用户不存在！");
        }
        return userMapper.queryLowPson(infoId.getOpId(),infoId.getId(),infoId.getPostId(),infoId.getBranchId(),infoId.getRoleId());
    }

    @Override
    public List<Person> queryHeadPson(String userId, Integer stationId) {
        UserInfoId infoId = null;
        if(stationId!=null&&stationId!=0){
            infoId = userMapper.queryUserInfoId(userMapper.queryPsonByStationId(stationId));
        }else {
            infoId = userMapper.queryUserInfoId(userId);
        }
        if (infoId == null){
            throw new OperationException("用户不存在！");
        }
        System.out.println(infoId.toString());
        List<Person> list = userMapper.queryHeadPson(infoId.getPostId(),infoId.getOpId(),infoId.getBranchId(),infoId.getBrId());
        if (list == null || list.size() ==0){
            list = userMapper.queryHeadPsonDefault(infoId.getBrId());
        }
        return list;
    }

    @Override
    public List<Branch> queryBranchByUserId(String userId) {
        if (userId == null){
            return userMapper.queryBranchByUserId(null,null,null);
        }
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
        if (infoId == null){
            throw new OperationException("用户不存在！");
        }
        List<Branch> list = userMapper.queryBranchByUserId(infoId.getOpId(),infoId.getBrId(),infoId.getBranchId());
        return list;
    }

    @Override
    public List<OpCenPerson> queryPsonByBranchId(String userId, String branchId) {
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
        if (infoId == null){
            throw new OperationException("用户不存在！");
        }
        List<OpCenPerson> list = userMapper.queryPsonByBranchId(userId,infoId.getOpId(),infoId.getBranchId(),branchId,infoId.getPostId());
        return list;
    }

    @Override
    public void changePassword(String userId,String oldPwd,String newPwd) {
        Person person = userMapper.findByIdAndPassword(userId,FormatUtil.string2MD5(oldPwd));
        if (person == null){
            throw new OperationException("初始密码错误！");
        }
        userMapper.changePassword(userId,FormatUtil.string2MD5(newPwd));
    }

    @Override
    public void saveHeadImage(String userId, MultipartFile file) {
        try {
            userMapper.saveHeadImage(file.getBytes(),file.getOriginalFilename(),userId);
        } catch (IOException e) {
            e.printStackTrace();
            throw new OperationException("上传头像失败！");
        }
    }

    @Override
    public void saveGPS(String userId, String lnt, String lat, String address) {
        userMapper.saveGPS(lnt,lat,address,userId);
    }

    @Override
    public List<PositionPerson> queryPsonByUserId(String userId, Integer pageNum, String keyword) {
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
        PageHelper.startPage(pageNum+1,20);
        List<PositionPerson> list = userMapper.queryPsonByUserId(userId,infoId.getOpId(),infoId.getBranchId(),infoId.getPostId(),infoId.getRoleId(),keyword);
        return list;
    }

    @Override
    public List<PositionPerson> queryNearPson(String userId, String lat, String lnt) {
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
        Double latitude = Double.parseDouble(lat);
        Double longitude = Double.parseDouble(lnt);
        Double degree = (24901 * 1609) / 360.0;
        double raidusMile = 50000;
        Double dpmLat = 1 / degree;
        Double radiusLat = dpmLat * raidusMile;
        Double minLat = latitude - radiusLat;
        Double maxLat = latitude + radiusLat;
        Double mpdLng = degree * Math.cos(latitude * (Math.PI / 180));
        Double dpmLng = 1 / mpdLng;
        Double radiusLng = dpmLng * raidusMile;
        Double minLng = longitude - radiusLng;
        Double maxLng = longitude + radiusLng;
        List<PositionPerson> list = userMapper.queryNearPson(infoId.getPostId(),userId,infoId.getOpId(),infoId.getBranchId(),minLat,maxLat,minLng,maxLng,lnt,lat);
        return list;
    }

    @Override
    public boolean verifyCode(String phoneNum) {
        UserInfoId infoId = userMapper.verifyCode(phoneNum);
        if (infoId==null){
            throw new OperationException("该手机号未绑定用户！");
        }
        String code = String.valueOf(FormatUtil.getRandNum(1000,9999));
        SendSmsResponse res = null;
        try {
            res = VerifyCodeUtil.sendSms(phoneNum,code);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new OperationException("发送验证码失败！");
        }
        if(res.getCode() != null && res.getCode().equals("OK")){
            CacheManager cacheManager = CacheManager.newInstance();
            Ehcache cache = cacheManager.getEhcache("ehCache");
            cache.put(new Element(phoneNum,code));
            return true;
        }else {
            throw new OperationException(res.getMessage());
        }
    }

    @Override
    public boolean checkCodeAndChangePassword(String phoneNum, String code, String password) {
        Ehcache cache = cacheManager.getEhcache("ehCache");
        if(cache.get(phoneNum)==null){
            throw new OperationException("验证码已失效！");
        }
        System.out.println(cache.get(phoneNum).getObjectValue());
        if(!code.equals(cache.get(phoneNum).getObjectValue())){
            throw new OperationException("验证码不匹配！");
        }
        userMapper.checkCodeAndChangePassword(FormatUtil.string2MD5(password),phoneNum);
        cache.remove(phoneNum);
        return true;
    }

    @Override
    public List<FaultLevel> queryBranchByMtStock(String userId) {
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
//        String sql ="select isnull(c.name,d.name) branchName,isnull(c.id,d.id) branchId,a.name from maint_pson a left join op_cen b on a.op_id=b.id left join branch_ofc c on b.br_id=c.id left join branch_ofc d on a.branch_id=d.id where a.id="+userId;
//        List<Map<String,Object>> mpList = statisticsMapper.queryFaultStatistics(sql);
        List<FaultLevel> list = new ArrayList<>();
        if (infoId == null||(infoId.getBrId() == null && infoId.getBranchId() == null)){
            list = userMapper.searchBranch("0",null);
            return list;
        }
        if (infoId.getBrId() != null){
            list = userMapper.searchBranch("1",infoId.getBrId().toString());
        }
        if (infoId.getBranchId() != null){
            list = userMapper.searchBranch("1",infoId.getBranchId().toString());
        }
        return list;
    }
    
    @Override
    public List<EquipReason> queryReason(Integer modelId){
    	List<EquipReason> list = userMapper.queryReason(modelId);
    	return list;
    };
    @Override
    public List<EquipReason> queryReason1(Integer modelId,String reason){
    	List<EquipReason> list = userMapper.queryReason1(modelId,reason);
    	return list;
    };
    
    @Override
    public Integer insertEquipReason(EquipReason reason) {
    	Integer id = userMapper.insertEquipReason(reason);
    	return id;
    };
    @Override
    public Integer insertEquipLog(EquipLog log) {
    	Integer id = userMapper.insertEquipLog(log);
    	return id;
    };
    @Override
    public Integer queryPsonCountByUserId(int userId) {
    	Integer count = userMapper.queryPsonCountByUserId(userId);
    	return count;
    };
    
    @Override
    public List<Equip> queryAllEquip() {
    	List<Equip> list = userMapper.queryAllEquip();
    	return list;
    };
    
    @Override
    public void updateAllEquip(List<Equip> list) {
    	userMapper.updateAllEquip(list);
    };
}
